﻿using CommonTools.Messages;
using CommonViews.Impls;
using CommonViews.Messages;
using CommunityToolkit.Mvvm.Messaging;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CommonViews.Views
{
    /// <summary>
    /// LogView.xaml 的交互逻辑
    /// </summary>
    public partial class LogView : UserControl
    {
        public LogView()
        {
            InitializeComponent();

            _InitLog();

            button_clear.Click += Button_clear_Click;

            Serilog.Log.Information("【系统】日志准备好");
            WeakReferenceMessenger.Default.Register<OnExitAppMessage>(this, (r, m) => { 
                _CloseLog();
            });

            WeakReferenceMessenger.Default.Register<LogMessage>(this, (r, m) => {

                Dispatcher.Invoke(() => {
                    dataGrid_log.ScrollIntoView(m.LogItem);
                });
                
            });
        }

        private void Button_clear_Click(object sender, RoutedEventArgs e)
        {
            LogViewSink.LogItems.Clear();
        }

        void _InitLog()
        {
            Serilog.Log.Logger = new LoggerConfiguration()
                .WriteTo.Sink(new Impls.LogViewSink())
                .WriteTo.File("LOGS/log.txt")
                .WriteTo.SQLite("LOGS/log.db")
                .CreateLogger();
        }
        void _CloseLog()
        {
            if (Serilog.Log.Logger != null)
            {
                Serilog.Log.CloseAndFlush();
            }
        }
    }
}
